import { FormProps } from "@/components/modal/form.modal"
import { Field_FormSave } from "@/components/utils/field.list"
import adminMenuService from "@/services/admin.menu.service"
import React, { useCallback } from "react"

import adminPermissionsService from "@/services/admin.permission.service"
import { FormRender } from "@whzhuke/antd"
import { arrayCommon } from "@whzhuke/common"

import { useFetch } from "@whzhuke/usehook"
import useForm from "antd/es/form/hooks/useForm"
import { MenuType } from "@whzhuke/interface"

interface Props {
  permissionId: number
}
export const PermissionsMenu: React.FC<Props & FormProps> = props => {
  const { permissionId, onDone } = props
  const [form] = useForm()
  const onFinish = useCallback(
    value => {
      adminPermissionsService.bindingPermissionMenu({ permissionId, resourceIds: value.data, type: 2 }).then(() => {
        useFetch.clear(adminPermissionsService.queryPermissionMenus, [{ permissionId: permissionId, type: 2 }])
        onDone?.()
      })
    },
    [permissionId]
  )
  const [{ data: menuList }] = useFetch(adminMenuService.all, [{ type: MenuType.SYS }])
  const [{ data: itemConfigList }] = useFetch(adminPermissionsService.queryPermissionMenus, [{ permissionId: permissionId, type: 2 }])
  const treeData = arrayCommon.doTree(
    menuList.map(m => ({ ...m, key: m.id, title: m.menuName })),
    "id",
    "parentId"
  )
  return (
    <FormRender
      form={form}
      initialValues={{ permissionId, data: itemConfigList.map(m => m) }}
      layout="horizontal"
      onFinish={onFinish}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ width: 600 }}
      fieldList={[
        {
          fieldType: "tree",
          formItemConfig: { required: !0, name: "data" },
          config: {
            checkable: !0,
            defaultExpandAll: !0,
            selectable: !1,
            treeData
          }
        },

        { ...Field_FormSave, formItemConfig: { wrapperCol: { offset: 8, span: 16 } } }
      ]}
      autoComplete="off"
    />
  )
}
